﻿using AutoMapper;
using Blog.Dto.Article;
using Blog.Model;
using Blog.Model.Dto.Article;
using Blog.Utility.ApiResult;
using Blog.Utility.Redis;
using IBaseService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using SqlSugar.Extensions;
using StackExchange.Redis;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Policy;

namespace Blog.Controllers
{
	[Route("api/[controller]")]
	[ApiController]
	[Authorize]
	public class ArticleController : ControllerBase
	{
        private readonly IArticleService _articleService;
		private readonly ILikeRelationService _likeRelationService;
		private readonly IDisLikeRelationService _dislikeRelationService;
		private readonly ICollectRelationService _collectRelationService;
		private readonly ICommentService _commentService;
		private readonly RedisConnecting _redisConnecting;
		private readonly ISqlSugarClient _sqlSugarClient;

		public ArticleController(IArticleService articleService, ILikeRelationService likeRelationService, IDisLikeRelationService dislikeRelationService, ICollectRelationService collectRelationService, ICommentService commentService, RedisConnecting redisConnecting, ISqlSugarClient sqlSugarClient = null)
		{
			_articleService = articleService;
			_likeRelationService = likeRelationService;
			_dislikeRelationService = dislikeRelationService;
			_collectRelationService = collectRelationService;
			_commentService = commentService;
			_redisConnecting = redisConnecting;
			_sqlSugarClient = sqlSugarClient;
		}

		/// <summary>
		/// 查询文章表（未发布）
		/// </summary>
		/// <returns></returns>
		[HttpGet("ArticleList")]
		public async Task<ActionResult<ApiResult>> QueryList()
		{
			var userId = Convert.ToInt32(this.User.FindFirst("Id").Value);
			var ArticleKey = $"Article:{userId}"; // 使用用户 ID 作为键的一部分
			IDatabase db = _redisConnecting.GetDatabase();

			// 尝试从 Redis 中获取文章列表
			var cachedArticles = await db.StringGetAsync(ArticleKey);

			if (cachedArticles.HasValue)
			{
				// 如果在 Redis 中找到了数据
				var list = JsonConvert.DeserializeObject<List<Article>>(cachedArticles);
				return ApiResultTool.Success(list);
			}
			else
			{
				// 如果在 Redis 中没有找到数据，则从数据库中查询
				var list = await _articleService.QueryAsync(x => x.AuthorID == userId && x.IsCheck != 2);

				// 将查询到的数据存储到 Redis 中
				await db.StringSetAsync(ArticleKey, JsonConvert.SerializeObject(list), TimeSpan.FromMinutes(30)); // 设置过期时间为 30 分钟

				return ApiResultTool.Success(list);
			}
		}
		/// <summary>
		/// 查询文章表（已审核）
		/// </summary>
		/// <returns></returns>
		[HttpGet("CheckedQueryList")]
		public async Task<ActionResult<ApiResult>> CheckedQueryList()
		{
			var list = await _articleService.QueryAsync(x => x.IsCheck == 2);
			return ApiResultTool.Success(list);
		}

		/// <summary>
		/// 创建文章
		/// </summary>
		/// <param name="titleName">文章标题</param>
		/// <param name="content">文章内容</param>
		/// <param name="articleTypeId">文章类型</param>
		/// <returns></returns>
		[HttpPost("CreateArticle")]
		public async Task<ActionResult<ApiResult>> CreateArticle(string titleName,string content,int articleTypeId) {
			Article article = new Article() { 
				Title = titleName,
				Content = content,
				CreationTime = DateTime.Now,
				LikeCount = 0,
				ViewCount = 0,
				ArticleTypeID = articleTypeId,
				AuthorID = Convert.ToInt32(this.User.FindFirst("Id").Value)
			};

			bool res =  await _articleService.CreateAsync(article);
			if (!res) return ApiResultTool.Fail("新增文章失败");
			return ApiResultTool.Success(article);
		}


		/// <summary>
		/// 删除文章
		/// </summary>
		/// <param name="id">文章ID</param>
		/// <returns></returns>
		[HttpPost("DeleteArticle")]
		public async Task<ActionResult<ApiResult>> DeleteArticle(int id) {
			bool res = await _articleService.DeleteByIdAsync(id);
			if(!res) return ApiResultTool.Fail("删除文章失败");
			return ApiResultTool.Success(res);
		}


		/// <summary>
		/// 修改文章
		/// </summary>
		/// <param name="id">文章ID</param>
		/// <param name="titleName">文章标题</param>
		/// <param name="content">文章内容</param>
		/// <param name="articleType">文章类型</param>
		/// <returns></returns>
		[HttpPost("UpdateArticle")]
		public async Task<ActionResult<ApiResult>> UpdateArticle(int id,string titleName, string content,int articleType)
		{
			Article article =  await _articleService.FindByIdAsync(id);
			if (article == null) return ApiResultTool.Fail("没有找到该文章");
			article.Title = titleName;
			article.Content = content;
			article.ArticleTypeID = articleType;


			bool res = await _articleService.EditAsync(article);
			if (!res) return ApiResultTool.Fail("修改文章失败");
			return ApiResultTool.Success(res);
		}



		/// <summary>
		/// 点击喜欢
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost("ClickLike")]
		public async Task<ActionResult<ApiResult>> ClickLike(int id)
		{
			IDatabase db = _redisConnecting.GetDatabase();
			Article article = await _articleService.FindByIdAsync(id);
			var userId = Convert.ToInt32(this.User.FindFirst("Id").Value);
			var likeKey = $"LikeRelation:User:{id}"; // 例如：LikeRelation:1
			var userLikeKey = $"{likeKey}:{id}"; // 例如：LikeRelation:User:1:Article:1:

			List<LikeRelation> likeRelations = await _likeRelationService.QueryAsync();
			LikeRelation likeRelation = likeRelations.FirstOrDefault(x => x.ArticleID == id);
			//不管你查没查到 都要往redis中插入一条数据
			if (likeRelations == null)
			{
				//执行数据库操作
				_sqlSugarClient.Ado.BeginTran();
				try
				{
					bool createRes = await _likeRelationService.CreateAsync(new LikeRelation { ArticleID = id, UserId = Convert.ToInt32(this.User.FindFirst("Id").Value), CreateDate = DateTime.Now });
					if (!createRes) return ApiResultTool.Fail("点赞失败");
					article.LikeCount += 1;
					await _articleService.EditAsync(article);
					_sqlSugarClient.Ado.CommitTran();
					//删除缓存
					await db.KeyDeleteAsync(likeKey);

				}
				catch (Exception ex)
				{
					_sqlSugarClient.Ado.RollbackTran();
					return BadRequest("发生错误: " + ex.Message);
				}
				return ApiResultTool.Fail("点赞成功");
			}
			//执行数据库操作
			_sqlSugarClient.Ado.BeginTran();
			try
			{
				bool deleteRes = await _likeRelationService.DeleteByIdAsync(likeRelation.Id);
				if (!deleteRes) return ApiResultTool.Fail("点赞取消失败");
				article.LikeCount -= 1;
				await _articleService.EditAsync(article);
				_sqlSugarClient.Ado.CommitTran();
				//删除缓存
				db.KeyDelete(likeKey);
				await db.KeyDeleteAsync(likeKey);
			}
			catch (Exception ex)
			{
				_sqlSugarClient.Ado.RollbackTran();
				return BadRequest("发生错误: " + ex.Message);
			}
			return ApiResultTool.Fail("点赞取消成功");


			//var value = db.StringGet(id.ToString());
			//if (value.IsNull == true)
			//{
			//	List<LikeRelation> likeRelations = await _likeRelationService.QueryAsync();
			//	LikeRelation likeRelation = likeRelations.FirstOrDefault(x => x.ArticleID == id);
			//	Article article = await _articleService.FindByIdAsync(id);
			//	if (likeRelation == null)
			//	{
			//		bool createRes = await _likeRelationService.CreateAsync(new LikeRelation { ArticleID = id, UserId = Convert.ToInt32(this.User.FindFirst("Id").Value), CreateDate = DateTime.Now });
			//		if (!createRes) return ApiResultTool.Fail("点赞失败");
			//		article.LikeCount += 1;
			//		await _articleService.EditAsync(article);
			//		return ApiResultTool.Fail("点赞成功");
			//	}
			//	bool deleteRes = await _likeRelationService.DeleteByIdAsync(likeRelation.Id);
			//	if (!deleteRes) return ApiResultTool.Fail("点赞取消失败");
			//	article.LikeCount -= 1;
			//	await _articleService.EditAsync(article);
			//	return ApiResultTool.Fail("点赞取消成功");
			//}

			//IDatabase db = _redisConnecting.GetDatabase();

			//// 获取当前用户的 ID
			//var userId = Convert.ToInt32(this.User.FindFirst("Id").Value);
			//var likeKey = $"Article:{id}:Likes"; // 例如：Article:1:Likes
			//var userLikeKey = $"{likeKey}:User:{userId}"; // 例如：Article:1:Likes:User:123

			//// 检查用户是否已经点赞
			//bool isLiked = db.SetContains(likeKey, userId); // 检查用户 ID 是否在集合中

			//if (!isLiked)
			//{
			//	// 用户没有点赞，进行点赞操作
			//	bool addRes = db.SetAdd(likeKey, userId); // 将用户 ID 添加到集合中
			//	if (!addRes) return ApiResultTool.Fail("点赞失败");

			//	// 更新 Redis 中的点赞计数
			//	db.StringIncrement($"Article:{id}:LikeCount"); // 增加点赞计数

			//	// 更新数据库中的文章点赞数
			//	Article article = await _articleService.FindByIdAsync(id);
			//	article.LikeCount += 1;
			//	await _articleService.EditAsync(article);

			//	return ApiResultTool.Success("点赞成功");
			//}
			//else
			//{
			//	// 用户已经点赞，进行取消点赞操作
			//	bool removeRes = db.SetRemove(likeKey, userId); // 从集合中移除用户 ID
			//	if (!removeRes) return ApiResultTool.Fail("点赞取消失败");

			//	// 更新 Redis 中的点赞计数
			//	db.StringDecrement($"Article:{id}:LikeCount"); // 减少点赞计数

			//	// 更新数据库中的文章点赞数
			//	Article article = await _articleService.FindByIdAsync(id);
			//	article.LikeCount -= 1;
			//	await _articleService.EditAsync(article);

			//	return ApiResultTool.Success("点赞取消成功");
			//}

		}



		/// <summary>
		/// 点击不喜欢
		/// </summary>
		/// <param name="id">文章ID</param>
		/// <returns></returns>
		[HttpPost("DisClickLike")]
		public async Task<ActionResult<ApiResult>> DisClickLike(int id)
		{
			List<DisLikeRelation> dislikeRelations = await _dislikeRelationService.QueryAsync();
			DisLikeRelation dislikeRelation = dislikeRelations.FirstOrDefault(x => x.ArticleID == id);
			Article article = await _articleService.FindByIdAsync(id);
			if (dislikeRelation == null)
			{
				bool createRes = await _dislikeRelationService.CreateAsync(new DisLikeRelation { ArticleID = id, UserId = Convert.ToInt32(this.User.FindFirst("Id").Value), CreateDate = DateTime.Now });
				if (!createRes) return ApiResultTool.Fail("点踩失败");
				article.DisLikeCount += 1;
				await _articleService.EditAsync(article);
				return ApiResultTool.Fail("点踩成功");
			}
			else
			{
				bool deleteRes = await _dislikeRelationService.DeleteByIdAsync(dislikeRelation.Id);
				if (!deleteRes) return ApiResultTool.Fail("点踩取消失败");
				article.DisLikeCount -= 1;
				await _articleService.EditAsync(article);
				return ApiResultTool.Fail("点踩取消成功");
			}
		}


		/// <summary>
		/// 点击收藏
		/// </summary>
		/// <param name="id">文章ID</param>
		/// <returns></returns>
		[HttpPost("CollectClick")]
		public async Task<ActionResult<ApiResult>> CollectClick(int id)
		{
			List<CollectRelation> collectRelations = await _collectRelationService.QueryAsync();	
			CollectRelation collectRelation = collectRelations.FirstOrDefault(x => x.ArticleID == id);
			Article article = await _articleService.FindByIdAsync(id);
			if (collectRelation == null)
			{
				bool createRes = await _collectRelationService.CreateAsync(new CollectRelation { ArticleID = id, UserId = Convert.ToInt32(this.User.FindFirst("Id").Value), CreateDate = DateTime.Now });
				if (!createRes) return ApiResultTool.Fail("收藏失败");
				article.CollectCount += 1;
				await _articleService.EditAsync(article);
				return ApiResultTool.Fail("收藏成功");
			}
			else
			{
				bool deleteRes = await _collectRelationService.DeleteByIdAsync(collectRelation.Id);
				if (!deleteRes) return ApiResultTool.Fail("取消收藏失败");
				article.CollectCount -= 1;
				await _articleService.EditAsync(article);
				return ApiResultTool.Fail("取消收藏成功");
			}
		}

		/// <summary>
		/// 文章发布
		/// </summary>
		/// <param name="id">文章ID</param>
		/// <returns></returns>
		[HttpPost("ArticleIssue")]
		public async Task<ActionResult<ApiResult>> ArticleIssue(int id) {
			ArticleRelationAuthor  articleRelationAuthor= await _articleService.QueryArticleAuthor(x=>x.Id == id);
			Article article = await _articleService.FindByIdAsync(id);
			if (articleRelationAuthor.RoleId == '1' && articleRelationAuthor.IsCheck == 0)
			{
				article.IsCheck = 2;
				bool res = await _articleService.EditAsync(article);
				if (!res) return ApiResultTool.Fail("发布失败");
				return ApiResultTool.Success("发布成功");
			}
			else {
				//审核中
				if (articleRelationAuthor.IsCheck == 1)
				{
					article.IsCheck = 2;
					bool res = await _articleService.EditAsync(article);
					if (!res) return ApiResultTool.Fail("发布失败");
					return ApiResultTool.Success("发布成功");
				}
				else if (articleRelationAuthor.IsCheck == 0)
				{
					article.IsCheck = 1;
					bool res = await _articleService.EditAsync(article);
					if (!res) return ApiResultTool.Fail("请求审核失败");
					return ApiResultTool.Success("正在审核中");
				}
				else {
					return ApiResultTool.Fail("已发布,请勿重复发布");
				}
			}
			
		}



		/// <summary>
		/// 分页查询
		/// </summary>
		/// <param name="mapper">映射</param>
		/// <param name="pageIndex">第几页</param>
		/// <param name="pageSize">一页有几个</param>
		/// <returns></returns>
		[HttpPost("GetPageList")]
		public async Task<ActionResult<ApiResult>> GetPageList([FromServices]IMapper mapper,int pageIndex,int pageSize) {
			RefAsync<int> total = 0;
			List<Article> articles =  await _articleService.QueryAsync(pageIndex, pageSize, total);
			if (articles.Count == 0) return ApiResultTool.Fail("未查询到指定数据");
			try
			{
				List<ArticleDto> articleDtos = mapper.Map<List<ArticleDto>>(articles);
				return ApiResultTool.Success(articleDtos,total);
			}
			catch (Exception)
			{
				return ApiResultTool.Fail("automap映射失败");
			}
		}


		/// <summary>
		/// 文章评论
		/// </summary>
		/// <param name="id">文章ID</param>
		/// <param name="context">文章内容</param>
		/// <returns></returns>
		[HttpPost("CreateComment")]
		public async Task<ActionResult<ApiResult>> CreateComment(int id,string context) {
			bool res = await _commentService.CreateAsync(new Comment() { Content = context,ArticleID = id,AuthorId = Convert.ToInt32(User.FindFirst("Id")?.Value) });
			if (!res) return ApiResultTool.Fail("评论失败");
			return ApiResultTool.Success("评论成功！");
		}

		
	}
}
